﻿using BootstrapBlazor.Components;
using BPM.Web.Shared.Data;
using BPM.Web.Shared.Dependencies;
using BPM.Web.Shared.Extensions;
namespace BPM.Web.Shared.Service;

[Scoped(typeof(ISysAppService))]
public class SysAppService : BaseService, ISysAppService
{
    private readonly IAppClient _appClient;
    public SysAppService(IAppClient client, ToastService toast) : base(toast)
        => _appClient = client;
    public Task<bool> AddAsync(SysApp input)
        => ExecuteAsync(_appClient.AddAsync(input.Adapt<AddAppInput>()));

    public Task<bool> DeleteAsync(IEnumerable<SysApp> input)
        => DeleteAsync(input.Adapts<SysApp, BaseId>().Select(x => _appClient.DeleteAsync(x)));

    public Task<QueryData<SysApp>> PageAsync(AppPageInput input)
        => QueryAsync(_appClient.PageAsync(input));

    public Task<bool> SetAsDefaultAsync(SysApp input)
        => ExecuteAsync(_appClient.SetAsDefaultAsync(input.Adapt<SetDefaultAppInput>()));

    public Task<bool> EditAsync(SysApp input)
        => ExecuteAsync(_appClient.EditAsync(input.Adapt<UpdateAppInput>()));

    public Task<SysApp?> DetailAsync(QueryAppInput input)
        => QueryAsync(_appClient.DetailAsync(input));

    public Task<List<SysApp>?> ListAsync()
        => QueryAsync<List<SysApp>>(_appClient.ListAsync());

    public Task<bool> ChangeStatusAsync(ChangeUserAppStatusInput input)
        => ExecuteAsync(_appClient.ChangeStatusAsync(input));

    public async Task<IEnumerable<SelectedItem>> GetSelectedAppsAsync()
    {
        var data = Enumerable.Empty<SelectedItem>();
        var result = await QueryAsync<List<SysApp>>(_appClient.ListAsync());
        if (result?.Count > 0)
        {
            data = result.Select(x => new SelectedItem()
            {
                Value = x.Code ?? string.Empty,
                Text = x.Name ?? string.Empty
            });
        }
        return data;
    }

    public IEnumerable<SelectedItem> GetSelectedItemAsync()
    {
        var data = Enumerable.Empty<SelectedItem>();
        var result = Task.Run(async () => await _appClient.ListAsync()).Result;
        if (result.Success && result.Data != null)
        {
            data = result.Data.Select(x => new SelectedItem()
            {
                Value = x.Code ?? string.Empty,
                Text = x.Name ?? string.Empty
            });
        }
        return data;
    }
}

